package com.lmx.repoDomain.tmodel.unpersis;

import io.katharsis.queryParams.QueryParams;
import io.katharsis.queryParams.RestrictedPaginationKeys;
import io.katharsis.queryParams.RestrictedSortingValues;
import io.katharsis.queryParams.params.SortingParams;
import io.katharsis.queryParams.params.TypedParams;

import java.util.Map;
import java.util.Map.Entry;

import javax.swing.SortOrder;

import com.google.common.collect.Maps;
import com.lmx.common.util.CommonUtil;

/**
 * 分页参数辅助类
 *
 * @author ytche
 * @date 2017年6月9日
 *
 */
public class QueryParam {
	private int currPage = 1;
	private int start = 0;
	private int size = 10;
	private Map<String, Object> filter = Maps.newHashMap();
	private Map<String, SortOrder> sort = Maps.newLinkedHashMap();

	public QueryParam(int start, int size) {
		this.start = start;
		this.size = size;
	}

	public QueryParam(QueryParams requestParams) {
		if (requestParams == null) {
			throw new NullPointerException("query params can not be null");
		}
		// 过滤条件
		Map<String, String> paramFilter = CommonUtil
				.getKeyMapByFilter(requestParams);
		for (Entry<String, String> e : paramFilter.entrySet()) {
			this.filter.put(e.getKey(), e.getValue());
		}
		// 分页信息
		Map<RestrictedPaginationKeys, Integer> pagintion = requestParams
				.getPagination();// 获取分页参数
		if (pagintion.size() > 0) { // 判断是否需要分页
			if (pagintion.get(RestrictedPaginationKeys.number) != null) {
				this.currPage = pagintion.get(RestrictedPaginationKeys.number);
			}
			if (pagintion.get(RestrictedPaginationKeys.size) != null) {
				this.size = pagintion.get(RestrictedPaginationKeys.size);
			}
		}
		this.start = this.currPage * this.size - 1;
		// 排序条件
		TypedParams<SortingParams> sortParams = requestParams.getSorting();
		Map<String, SortingParams> sortMap = sortParams.getParams();
		for (Entry<String, SortingParams> sortEntry : sortMap.entrySet()) {
			SortingParams sortParams2 = sortEntry.getValue();
			Map<String, RestrictedSortingValues> sort = sortParams2.getParams();
			for (Entry<String, RestrictedSortingValues> sortValue : sort
					.entrySet()) {
				if (RestrictedSortingValues.asc.equals(sortValue.getValue())) {
					this.sort.put(sortValue.getKey(), SortOrder.ASCENDING);
				} else {
					this.sort.put(sortValue.getKey(), SortOrder.DESCENDING);
				}
			}

		}
	}

	public int getCurrPage() {
		return currPage;
	}

	public void setCurrPage(int currPage) {
		this.currPage = currPage;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public Map<String, Object> getFilter() {
		return filter;
	}

	public void setFilter(Map<String, Object> filter) {
		this.filter = filter;
	}

	public Map<String, SortOrder> getSort() {
		return sort;
	}

	public void setSort(Map<String, SortOrder> sort) {
		this.sort = sort;
	}
}
